//
//  BillShowViewController.m
//  iEasyBill
//
//  Created by student on 14-5-9.
//  Copyright (c) 2014年 com.yly16. All rights reserved.
//

#define kmonthLabel 10
#define ktimeStrLabel 11
#define kpayLabel 12
#define koutLabel 13
#define kjieYuLabel 14

/*
 MJ友情提示：
 1> 在MJRefreshBaseView.h中：可以通过NeedAudio宏来控制是否需要刷新音效
 2> 在MJRefreshFooterView.m和MJRefreshHeaderView.m中可以修改刷新显示的文字
 3> 监听进入刷新状态有2种方式：
 * 设置delegate，通过代理方法监听
 * 设置beginRefreshingBlock，通过block回调监听
 4> 本框架兼容iPhone\iPad横竖屏
 */

// 1.主头文件
#import "MJRefresh.h"
#import "BillShowViewController.h"

@interface BillShowViewController ()<MJRefreshBaseViewDelegate>
{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    BOOL isFirstRe;//是不是第一次进入
    NSInteger year;
    NSInteger correntYear;
    float _moneyAddNumber;
}

@property (assign)BOOL isOpen;
@property (nonatomic,retain)NSIndexPath *selectIndex;
@property (nonatomic,strong)NSIndexPath *deleteIndexPath;
@property (nonatomic,retain)NSIndexPath *moneyIndexPath;
@property (nonatomic,retain)NSIndexPath *iIndexPath;
@end

@implementation BillShowViewController



- (void)viewDidLoad
{
    [super viewDidLoad];

    //>>>>>>>>>>>>>>>>>>>>>
    radius = 138;
    bubbleRadius = 20;
    
    
    isFirstRe = YES;
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    year = [components year];
    correntYear = [components year];
    self.title = [NSString stringWithFormat:@"%d年",year];
    self.iYearBillList = [[NSMutableArray alloc]init];
    self.iYearBillList = [self showYearBillListByYear:year];
    self.iYearBillList = [self iYearBillListCompositorIsOrder:YES];
    
    self.tableView.delegate = self;
    // 防止block循环retain，所以用__unsafe_unretained
    __unsafe_unretained BillShowViewController *vc = self;
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = self.tableView;
    // 进入上拉加载状态就会调用这个方法
    _footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 增加5个假数据
        
        year++;
        self.title = [NSString stringWithFormat:@"%d年",year];
        self.iYearBillList = [self showYearBillListByYear:year];
        if (year == correntYear) {
            self.iYearBillList = [self iYearBillListCompositorIsOrder:YES];
        }
        // 2秒后刷新表格
        [vc performSelector:@selector(reloadDeals) withObject:nil afterDelay:2];
        
    };
    
    // 5.0.5秒后自动下拉刷新
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.1];
}
-(void)viewDidAppear:(BOOL)animated{
    self.view.frame = CGRectMake(0, 65, 320, 502);
    self.iYearBillList = [self showYearBillListByYear:year];
    if (year == correntYear) {
        self.iYearBillList = [self iYearBillListCompositorIsOrder:YES];
    }
    [self.tableView reloadData];
}
#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _header) { // 下拉刷新
            // 减少年份
            if (isFirstRe == NO) {
            year--;
            self.iYearBillList = [self showYearBillListByYear:year];
            self.title = [NSString stringWithFormat:@"%d年",year];
            if (year == correntYear) {
                self.iYearBillList = [self iYearBillListCompositorIsOrder:YES];
            }
            
        }else{
            isFirstRe = NO;
            [self performSelector:@selector(reloadDeals) withObject:nil afterDelay:0.2];
            return;
        }
        // 2秒后刷新表格
        [self performSelector:@selector(reloadDeals) withObject:nil afterDelay:2];
    }
}
#pragma mark 刷新数据
- (void)reloadDeals
{
    self.view.frame = CGRectMake(0, 65, 320, 502);
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}
//TODO:根据一个date得到这个date的一个月的开始日期到结束日期
- (NSString *)getBeginAndEndWithDate:(NSDate *)date{
    NSDate *newDate = date;
    double interval = 0;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];//设定周一为周首日
    BOOL ok;
    ok = [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit 可查年、月、周开始结束 “某个时间点”所在的“单元”的起始时间，以及起始时间距离“某个时间点”的时差（单位秒）
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }else {
        return nil;
    }
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"MM.dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    
    return [NSString stringWithFormat:@"%@-%@",beginString,endString];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}
//TODO:得到一年的所有账单
-(NSMutableArray *)showYearBillListByYear:(NSInteger)iyear
{
    NSMutableArray *rootList = [[NSMutableArray alloc]init];
    
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger correntyear = [components year];
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];           //设定时间格式,这里可以设置成自己需要的格式
    NSDate *Startdate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-01-01 00:00:00",iyear]];
    NSDate *Enddate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-12-31 00:00:00",iyear]];
    NSMutableArray *list = [[DatabaseManager shareManager]showBillByDate:Startdate toDate:Enddate toType:nil];
    dateFormat = [[NSDateFormatter alloc] init];
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    [dateFormat setDateFormat:@"MM"];
    if (correntyear == iyear) {
        for (iBill *theBill in list) {
            NSMutableDictionary *rootDictionary = [[NSMutableDictionary alloc]init];
            
            NSInteger month = [[dateFormat stringFromDate:theBill.billTime] integerValue];
            if (rootList.count == 0) {
                [rootDictionary setValue:@(month) forKey:@"month"];
                [rootDictionary setObject:[self getBeginAndEndWithDate:theBill.billTime] forKey:@"time"];
                NSMutableArray *array = [[NSMutableArray alloc]init];
                [array addObject:theBill];
                float payMoney = 0.0;
                float outMoney = 0.0;
                if (theBill.isPayOut.boolValue == YES) {
                    payMoney = theBill.billMoney.floatValue;
                }
                else{
                    outMoney = theBill.billMoney.floatValue;
                }
                [rootDictionary setObject:@(payMoney) forKey:@"payMoney"];
                [rootDictionary setObject:@(outMoney) forKey:@"outMoney"];
                [rootDictionary setObject:array forKey:@"list"];
                [rootList addObject:rootDictionary];
            }
            else{
                BOOL isOK = NO;
                for (NSMutableDictionary *dic in rootList) {
                    if ([[dic objectForKey:@"month"] integerValue] == month) {
                        NSMutableArray *array = [dic objectForKey:@"list"];
                        [array addObject:theBill];
                        float payMoney = [[dic objectForKey:@"payMoney"] floatValue];
                        float outMoney = [[dic objectForKey:@"outMoney"] floatValue];
                        if (theBill.isPayOut.boolValue == YES) {
                            payMoney += theBill.billMoney.floatValue;
                        }
                        else{
                            outMoney += theBill.billMoney.floatValue;
                        }
                        [dic setObject:@(payMoney) forKey:@"payMoney"];
                        [dic setObject:@(outMoney) forKey:@"outMoney"];
                        [dic setObject:array forKey:@"list"];
                        isOK = YES;
                        break;
                    }
                }
                if (isOK == NO) {
                    [rootDictionary setValue:@(month) forKey:@"month"];
                    [rootDictionary setObject:[self getBeginAndEndWithDate:theBill.billTime] forKey:@"time"];
                    NSMutableArray *array = [[NSMutableArray alloc]init];
                    [array addObject:theBill];
                    float payMoney = 0.0;
                    float outMoney = 0.0;
                    if (theBill.isPayOut.boolValue == YES) {
                        payMoney = theBill.billMoney.floatValue;
                    }
                    else{
                        outMoney = theBill.billMoney.floatValue;
                    }
                    [rootDictionary setObject:@(payMoney) forKey:@"payMoney"];
                    [rootDictionary setObject:@(outMoney) forKey:@"outMoney"];
                    [rootDictionary setObject:array forKey:@"list"];
                    [rootList addObject:rootDictionary];
                }
                
            }
        }
    }
    else{
        for (int i = 12; i > 0; i--) {
            NSMutableDictionary *rootDictionary = [[NSMutableDictionary alloc]init];
            Startdate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-%d-05 00:00:00",iyear,i]];
            [rootDictionary setValue:@(i) forKey:@"month"];
            [rootDictionary setObject:[self getBeginAndEndWithDate:Startdate] forKey:@"time"];
            NSMutableArray *array = [[NSMutableArray alloc]init];
            float payMoney = 0.0;
            float outMoney = 0.0;
            [rootDictionary setObject:@(payMoney) forKey:@"payMoney"];
            [rootDictionary setObject:@(outMoney) forKey:@"outMoney"];
            [rootDictionary setObject:array forKey:@"list"];
            for (int c = 0; c <list.count; c++)  {
                iBill *theBill = [list objectAtIndex:c];
                NSInteger month = [[dateFormat stringFromDate:theBill.billTime] integerValue];
                
                
                if (month == i) {
                    
                    NSMutableArray *array = [rootDictionary objectForKey:@"list"];
                    [array addObject:theBill];
                    float payMoney = [[rootDictionary objectForKey:@"payMoney"] floatValue];
                    float outMoney = [[rootDictionary objectForKey:@"outMoney"] floatValue];
                    if (theBill.isPayOut.boolValue == YES) {
                        payMoney += theBill.billMoney.floatValue;
                    }
                    else{
                        outMoney += theBill.billMoney.floatValue;
                    }
                    [rootDictionary setObject:@(payMoney) forKey:@"payMoney"];
                    [rootDictionary setObject:@(outMoney) forKey:@"outMoney"];
                    [rootDictionary setObject:array forKey:@"list"];
                
                }
            }
            NSMutableArray *temparray = [rootDictionary objectForKey:@"list"];
            if (temparray.count == 0) {
                [temparray addObject:@"没有数据"];
            }
            [rootList addObject:rootDictionary];
        }
    }
    
    return rootList;
}
-(NSMutableDictionary*)showAllBillMoney{
    NSMutableDictionary *rootDic = [[NSMutableDictionary alloc]init];
    float payMoney = 0.0;
    float outMoney = 0.0;
    for (NSDictionary *dic in self.iYearBillList) {
        payMoney += [[dic objectForKey:@"payMoney"] floatValue];
        outMoney += [[dic objectForKey:@"outMoney"] floatValue];
    }
    [rootDic setObject:@(payMoney) forKey:@"payMoney"];
    [rootDic setObject:@(outMoney) forKey:@"outMoney"];
    return rootDic;
}
//排序
-(NSMutableArray*)iYearBillListCompositorIsOrder:(BOOL)Order{
    NSMutableArray *list = [[NSMutableArray alloc]init];
    int count = self.iYearBillList.count;
    for (int i = 0;  i < count-1; i++) {
        for (int k = 0; k < count -1; k++) {
            NSDictionary *currentdic = [self.iYearBillList objectAtIndex:k];
            NSDictionary *nextdic = [self.iYearBillList objectAtIndex:k+1];
            int a = [[currentdic objectForKey:@"month"] integerValue];
            int b = [[nextdic objectForKey:@"month"] integerValue];
            if (Order == YES) {
                if (a < b) {
                    [self.iYearBillList exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                }
            }
            else{
                if (a > b) {
                    [self.iYearBillList exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                }
            }
        }
    }
    NSInteger maxMonth = [[[self.iYearBillList firstObject] objectForKey:@"month"] integerValue];
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];           //设定时间格式,这里可以设置成自己需要的格式
    
    for (int i = maxMonth; i > 0; i--) {
        NSMutableDictionary *rootDictionary = [[NSMutableDictionary alloc]init];
        NSDate *Startdate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-%d-05 00:00:00",year,i]];
        [rootDictionary setValue:@(i) forKey:@"month"];
        [rootDictionary setObject:[self getBeginAndEndWithDate:Startdate] forKey:@"time"];
        NSMutableArray *array = [[NSMutableArray alloc]init];
        float payMoney = 0.0;
        float outMoney = 0.0;
        [rootDictionary setObject:@(payMoney) forKey:@"payMoney"];
        [rootDictionary setObject:@(outMoney) forKey:@"outMoney"];
        [rootDictionary setObject:array forKey:@"list"];
        for (NSMutableDictionary *dic in self.iYearBillList) {
            if ([[dic objectForKey:@"month"]integerValue] == i) {
                rootDictionary = dic;
                break;
            }
        }
        NSMutableArray *temparray = [rootDictionary objectForKey:@"list"];
        if (temparray.count == 0) {
            [temparray addObject:@"没有数据"];
        }
        [list addObject:rootDictionary];
    
    }
    return list;
}
//将账单以日期进行排序
-(NSMutableArray*)billListCompositorFormList:(NSMutableArray*)list IsOrder:(BOOL)Order{
    int count = list.count;
    for (int i = 0;  i < count-1; i++) {
        for (int k = 0; k < count -1; k++) {
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
            [dateFormatter setDateFormat:@"dd"];
            iBill *currentBill = [list objectAtIndex:k];
            iBill *nextBill = [list objectAtIndex:k+1];
           
            int a = [[dateFormatter stringFromDate:currentBill.billTime] integerValue];
            int b = [[dateFormatter stringFromDate:nextBill.billTime] integerValue];
            if (Order == YES) {
                if (a < b) {
                    [list exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                }
            }
            else{
                if (a > b) {
                    [list exchangeObjectAtIndex:k withObjectAtIndex:k+1];
                }
            }
        }
    }
    return list;
}

-(NSIndexPath*)indexsPathFromView:(UIView*)view
{
    UIView *parentView = [view superview];
    
    while (![parentView isKindOfClass:[UITableViewCell class]] && parentView!=nil) {
        parentView = parentView.superview;
    }
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell*)parentView];
    NSLog(@"%d",indexPath.row);
    return indexPath;
}
-(void)showBillEdit:(UIButton*)sender{
    
    
    self.deleteIndexPath = [self indexsPathFromView:sender];
    self.iIndexPath = [self indexsPathFromView:sender];
    
//    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.deleteIndexPath];
    
    CGPoint point = [sender convertPoint:point fromView:self.view];
    point.x = - point.x + sender.frame.size.width/2;
    point.y = - point.y +sender.frame.size.height/2;
    if(shareBubbles) {
        shareBubbles = nil;
    }
    shareBubbles = [[AAShareBubbles alloc] initWithPoint:point radius:radius inView:self.view];
    shareBubbles.delegate = self;
    shareBubbles.bubbleRadius = bubbleRadius;
    shareBubbles.showFacebookBubble = YES;
    shareBubbles.showTwitterBubble = YES;
//    shareBubbles.showGooglePlusBubble = YES;
//    shareBubbles.showMailBubble = YES;
//    shareBubbles.showTumblrBubble = YES;

    [shareBubbles show];

    
}
-(void)aaShareBubbles:(AAShareBubbles *)shareBubbles tappedBubbleWithType:(AAShareBubbleType)bubbleType{
    if (bubbleType  == AAShareBubbleTypeFacebook) {
        [self performSegueWithIdentifier:@"liushui2modfiy" sender:self];
    }
    else{
//        self.deleteIndexPath=indexPath;
        UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要删除吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil];
        [alert show];
    }
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return self.iYearBillList.count+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (self.isOpen) {
        if (self.selectIndex.section == section) {
            NSInteger ret=[[[self.iYearBillList objectAtIndex:section-1] objectForKey:@"list"] count]+1;
            return ret;
        }
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        //显示第一个cell
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        NSDictionary *dic = [self showAllBillMoney];
        float shengyu = [[dic objectForKey:@"payMoney"] floatValue] - [[dic objectForKey:@"outMoney"] floatValue];
        UILabel *shengyuLabel = (UILabel*)[cell viewWithTag:21];
        shengyuLabel.text = [NSString stringWithFormat:@"¥%.2f",shengyu];
        if (shengyu > 0) {
            [shengyuLabel setTextColor:[UIColor greenColor]];
        }
        else{
            [shengyuLabel setTextColor:[UIColor redColor]];
        }
        UILabel *allPayLabel = (UILabel*)[cell viewWithTag:22];
        allPayLabel.text = [NSString stringWithFormat:@"¥%.2f",[[dic objectForKey:@"payMoney"] floatValue]];
        UILabel *allOutLabel = (UILabel*)[cell viewWithTag:23];
        allOutLabel.text = [NSString stringWithFormat:@"¥%.2f",[[dic objectForKey:@"outMoney"] floatValue]];
        self.moneyIndexPath = indexPath;
        _moneyAddNumber = 0;
        [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateMoneyNumber:) userInfo:self repeats:YES];
        
        return cell;
    }
    if (self.isOpen&&self.selectIndex.section == indexPath.section&&indexPath.row!=0) {
        
        if ([[[[self.iYearBillList objectAtIndex:indexPath.section-1] objectForKey:@"list"] firstObject] isKindOfClass:[NSString class]]) {
            //显示第三个cell
            static NSString *CellIdentifier = @"Cell3";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
            UILabel *label = (UILabel*)[cell viewWithTag:41];
            label.text = @"没有数据";
            return cell;
        }
        //显示第二个cell
        static NSString *CellIdentifier = @"Cell2";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        NSMutableArray *array = [[self.iYearBillList objectAtIndex:indexPath.section-1] objectForKey:@"list"];
        array = [self billListCompositorFormList:array IsOrder:YES];
        
        iBill *aBill = [array objectAtIndex:indexPath.row-1];
        
        NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
        //NSDate *date_ = [NSDate date];
        [formatter setTimeStyle:NSDateFormatterMediumStyle];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        NSInteger unitFlags = NSYearCalendarUnit |
        NSMonthCalendarUnit |
        NSDayCalendarUnit |
        NSWeekdayCalendarUnit |
        NSHourCalendarUnit |
        NSMinuteCalendarUnit |
        NSSecondCalendarUnit;
        //int week=0;week1是星期天,week7是星期六;
        comps = [calendar components:unitFlags fromDate:aBill.billTime];
        NSString *week = [self week:[comps weekday]];
        NSInteger day = [comps day];
        UILabel *dayLabel = (UILabel*)[cell viewWithTag:1];
        UILabel *weekLabel = (UILabel*)[cell viewWithTag:2];
        UIImageView *subtypeImage = (UIImageView*)[cell viewWithTag:3];
        UIImageView *liftImage = (UIImageView*)[cell viewWithTag:13]; //左边的ImageView
        UIImageView *rightImage = (UIImageView*)[cell viewWithTag:23];//右边的ImageView
        UILabel *rightTypeLabel = (UILabel*)[cell viewWithTag:4];
        UILabel *PayLabel = (UILabel*)[cell viewWithTag:5];
        UILabel *outLabel = (UILabel*)[cell viewWithTag:15];
        UILabel *rightMoneyLabel = (UILabel*)[cell viewWithTag:6];
        UIView *lineView = (UIView*)[cell viewWithTag:7];
        
        UILabel *LifttypeLabel = (UILabel*)[cell viewWithTag:14];
        UILabel *LiftmoneyLabel = (UILabel*)[cell viewWithTag:16];
        UIButton *billButton = (UIButton*)[cell viewWithTag:50];
        [billButton addTarget:self action:@selector(showBillEdit:) forControlEvents:UIControlEventTouchUpInside];
        
        iBillTypeSub *sub = [[DatabaseManager shareManager]showBillSubTypeByTypeID:aBill.billTypeSubID.integerValue];
        [PayLabel setHidden:YES];
        [outLabel setHidden:YES];
        if (indexPath.row == 1) {
            [PayLabel setHidden:NO];
            [outLabel setHidden:NO];
            weekLabel.text = week;
            dayLabel.text = [NSString stringWithFormat:@"%d",day];
            [lineView setBackgroundColor:[UIColor blackColor]];
        }else{
            iBill *oldBill = [array objectAtIndex:indexPath.row-2];
            comps = [calendar components:unitFlags fromDate:oldBill.billTime];
            if ([comps day] != day) {
                weekLabel.text = week;
                dayLabel.text = [NSString stringWithFormat:@"%d",day];
                [lineView setBackgroundColor:[UIColor blackColor]];
            }
            else{
                weekLabel.text = @"";
                dayLabel.text = @"";
                [lineView setBackgroundColor:[UIColor clearColor]];
            }
        }
        subtypeImage.image = [UIImage imageWithData:sub.typeSubImageData];
        if (aBill.isPayOut.boolValue == NO) {
            
            rightTypeLabel.text = sub.typeSubName;
            //isPayOutkLabel.text = [NSString stringWithFormat:@"%@",aBill.isPayOut.boolValue?@"收入":@"支出"];
            rightMoneyLabel.text = [NSString stringWithFormat:@"¥%.2f",aBill.billMoney.floatValue];
            LiftmoneyLabel.text = @"";
            LifttypeLabel.text = @"";
            
            rightImage.image = [UIImage imageWithData:aBill.billImageData];
            [liftImage setHidden:YES];
            [rightImage setHidden:NO];
        }
        else{
            
            LifttypeLabel.text = sub.typeSubName;
            LiftmoneyLabel.text = [NSString stringWithFormat:@"¥%.2f",aBill.billMoney.floatValue];
            rightMoneyLabel.text = @"";
            rightTypeLabel.text = @"";
            
            liftImage.image = [UIImage imageWithData:aBill.billImageData];
            [liftImage setHidden:NO];
            [rightImage setHidden:YES];
        }
        
        self.tableView.separatorStyle = NO;
        return cell;
        
    }
    else{
        static NSString *CellIdentifier = @"Cell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        NSDictionary *aDic = [self.iYearBillList objectAtIndex:indexPath.section-1];
        UILabel *monthLabel = (UILabel*)[cell viewWithTag:kmonthLabel];
        monthLabel.text = [NSString stringWithFormat:@"%d月",[[aDic objectForKey:@"month"] integerValue]];
        
        
        UILabel *monthStrLabel = (UILabel*)[cell viewWithTag:ktimeStrLabel];
        monthStrLabel.text = [aDic objectForKey:@"time"];
        
        UILabel *payLabel = (UILabel*)[cell viewWithTag:kpayLabel];
        payLabel.text = [NSString stringWithFormat:@"%.2f",[[aDic objectForKey:@"payMoney"] floatValue]];
        
        UILabel *outLabel = (UILabel*)[cell viewWithTag:koutLabel];
        outLabel.text = [NSString stringWithFormat:@"¥%.2f",[[aDic objectForKey:@"outMoney"] floatValue]];
        
        UILabel *JieYULabel = (UILabel*)[cell viewWithTag:kjieYuLabel];
        JieYULabel.text = [NSString stringWithFormat:@"¥%.2f",[[aDic objectForKey:@"payMoney"] floatValue] - [[aDic objectForKey:@"outMoney"] floatValue]];
        return cell;
    }
    
    
    // Configure the cell...
    
}

- (void)didSelectCellRowFirstDo:(BOOL)firstDoInsert nextDo:(BOOL)nextDoInsert
{
    
    self.isOpen = firstDoInsert;
    self.view.frame = CGRectMake(0, 65, 320, 502);
    UITableViewCell *cell1 = [self.tableView cellForRowAtIndexPath:self.selectIndex];
    UIImageView* rightImageview=(UIImageView*)[cell1 viewWithTag:3];
    if (firstDoInsert) {
        rightImageview.image=[UIImage imageNamed:@"UpAccessory.png"];
    }else
    {
        rightImageview.image = [UIImage imageNamed:@"DownAccessory.png"];
    }
	[self.tableView beginUpdates];//重新加载tableView的数据
	
    int section = self.selectIndex.section;
    int contentCount = [[[self.iYearBillList objectAtIndex:section-1] objectForKey:@"list"] count];//获取每个section的cell个数
	NSMutableArray *rowToInsert = [[NSMutableArray alloc] init];
	for (NSUInteger i = 1; i < contentCount + 1; i++) {
		NSIndexPath* indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
		[rowToInsert addObject:indexPathToInsert];
	}//此处i＝1是由于我们展开section是从第1个cell开始加载的
	if (firstDoInsert)
    {
        [self.tableView insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
        //给tableview插入指定IndexPath,UITableViewRowAnimationLeft 是指定子cell的出现方法
    }else
    {
        [self.tableView deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationBottom];//给tableview删除指定IndexPath
    }
	[self.tableView endUpdates];//重新加载tableView的数据
    
    if (nextDoInsert) {
        self.isOpen = YES;
        self.selectIndex = [self.tableView indexPathForSelectedRow];
        [self didSelectCellRowFirstDo:YES nextDo:NO];
    }
    if (self.isOpen)
        [self.tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];//UITableViewScrollPositionBottom指定section的动画方式为向下展开；此方法默认为UITableViewScrollPositionBottom 还有：  UITableViewScrollPositionTop等
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@">>>>>>>>>>>>>>>>");
    self.iIndexPath = indexPath;
    if (indexPath.section == 0) {
        return;
    }
    if (indexPath.row == 0) {
        if ([indexPath isEqual:self.selectIndex]) {
            self.isOpen = NO;
            [self didSelectCellRowFirstDo:NO nextDo:NO];
            self.selectIndex = nil;
        }else
        {
            if (!self.selectIndex) {
                self.selectIndex = indexPath;
                [self didSelectCellRowFirstDo:YES nextDo:NO];//调用MyMethod方法给tableView绑定相关要求；
            }else
            {
                [self didSelectCellRowFirstDo:NO nextDo:YES];
            }
        }
    }
    else{
        //        NSDictionary *dic = [_dataList objectAtIndex:indexPath.section];
        //        NSArray *list = [dic objectForKey:@"list"];
        //        NSString *item=[[NSString alloc]init];
        //        if ([list[0] isKindOfClass:[NSString class]]) {
        //            item=@"没有记录";
        //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:item message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil];
        //            [alert show];
        //        }else{
        //            Bill *abill=list[indexPath.row-1];
        //            [self performSegueWithIdentifier:@"toUpdate" sender:abill];
        //        }
        //self.bi
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //选中后的反显颜色即刻消失 一切操作结束才取消反映色
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    
    if (self.isOpen&&self.selectIndex.section == indexPath.section&&indexPath.row!=0)
    {
        //cell2
        return YES;
    }
    return NO;
}


 //Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        
        self.deleteIndexPath=indexPath;
        UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要删除吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil];
        [alert show];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }
    else{
        if (indexPath.row != 0) {
            return 88;
        }
    }
    return 44;
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */
//TODO:>>>>>>>>
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        NSMutableArray *array = [[self.iYearBillList objectAtIndex:self.deleteIndexPath.section-1] objectForKey:@"list"];
        array = [self billListCompositorFormList:array IsOrder:YES];
        iBill *aBill = [array objectAtIndex:self.deleteIndexPath.row-1];
        [array removeObjectAtIndex:self.deleteIndexPath.row - 1];
        [[DatabaseManager shareManager] removeABillIndex:aBill];
        [self.tableView deleteRowsAtIndexPaths:@[self.deleteIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        self.iYearBillList = [self showYearBillListByYear:year];
        [self iYearBillListCompositorIsOrder:YES];
        [self.tableView reloadData];
    }
}
-(void)updateMoneyNumber:(NSTimer*)sender{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.moneyIndexPath];
    NSDictionary *dic = [self showAllBillMoney];
    
    float payMoney = [[dic objectForKey:@"payMoney"] floatValue];
    float outMoney = [[dic objectForKey:@"outMoney"] floatValue];
    
    float key = 0.0;
    float bili = 0.0;
    if (payMoney == 0) {
        key = 10.0;
    }if (payMoney != 0){
        bili = outMoney / payMoney;
        key = 62*bili+10;
    }
    UIView *bgView = (UIView*)[cell viewWithTag:31];
    if (bili < 0.2) {
        bgView.backgroundColor = [UIColor yellowColor];
    }
    if (bili > 1.0) {
        key = 62*(1 - (bili - 1))+10;
        bgView.backgroundColor = [UIColor orangeColor];
    }
    if (key < 0) {
        key = -key;
    }
    if (72-_moneyAddNumber < key+15) {
        [sender invalidate];
        UIImageView *imageView = (UIImageView*)[cell viewWithTag:32];
        if (payMoney == outMoney) {
            imageView.image = [UIImage imageNamed:@"batteryFull.png"];
        }
        if (payMoney == 0) {
            imageView.image = [UIImage imageNamed:@"batteryQue.png"];
        }
    }
    
    bgView.frame = CGRectMake(252, 72-_moneyAddNumber, 38, 1+_moneyAddNumber);
    _moneyAddNumber++;
}
-(NSString*)week:(NSInteger)week
{
    NSString *weekStr = nil;
    if(week==7)
    {
        weekStr=@"星期天";
    }else if(week==1){
        weekStr=@"星期一";
        
    }else if(week==2){
        weekStr=@"星期二";
        
    }else if(week==3){
        weekStr=@"星期三";
        
    }else if(week==4){
        weekStr=@"星期四";
        
    }else if(week==5){
        weekStr=@"星期五";
        
    }else if(week==6){
        weekStr=@"星期六";
        
    }
    return weekStr;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSObject *NewVC = [segue destinationViewController];
    
    NSDictionary *dic =[self.iYearBillList objectAtIndex:self.iIndexPath.section-1];
    NSLog(@"%d",self.iIndexPath.row-1);
    NSArray *array = [self billListCompositorFormList:[dic objectForKey:@"list"]  IsOrder:YES];
    iBill *aBill = [array objectAtIndex:self.iIndexPath.row-1];
    if ([segue.identifier isEqualToString:@"liushui2modfiy"]) {
        [NewVC setValue:aBill forKey:@"aBill"];
    }
    
}
@end
